<template>
  <div class="page-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-title">
        <div class="title-with-back">
          <el-button 
            type="primary" 
            :icon="ArrowLeft" 
            @click="$router.push('/tools')"
            class="blue-return-button"
            circle
          />
          <div class="title-content">
            <div class="title-main">
              <el-icon class="title-icon"><DataLine /></el-icon>
              <h2>StarRocks管理</h2>
            </div>
            <p class="page-description">
              <el-icon><Document /></el-icon>
              <span>StarRocks事务管理与任务监控，支持批量回滚、SQL执行、任务查询与停止</span>
            </p>
          </div>
        </div>
      </div>
    </div>

    <!-- 功能卡片区域 -->
    <div class="cards-container">
      <!-- StarRocks事务管理卡片 -->
      <el-card class="feature-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <div class="card-header-title">
              <el-icon class="card-icon"><Coin /></el-icon>
              <span>StarRocks事务管理</span>
            </div>
            <el-tag type="success" size="small">可用</el-tag>
          </div>
        </template>
        
        <div class="card-content">
          <p class="card-description">
            查询运行中的事务状态，执行批量回滚操作
          </p>
          
          <div class="feature-list">
            <div class="feature-item">
              <el-icon color="#67C23A"><Check /></el-icon>
              <span>事务查询</span>
            </div>
            <div class="feature-item">
              <el-icon color="#67C23A"><Check /></el-icon>
              <span>批量回滚操作</span>
            </div>
            <div class="feature-item">
              <el-icon color="#67C23A"><Check /></el-icon>
              <span>SQL执行</span>
            </div>
            <div class="feature-item">
              <el-icon color="#67C23A"><Check /></el-icon>
              <span>连接测试</span>
            </div>
          </div>
          
          <div class="card-actions">
            <el-button type="primary" @click="showTransactionDialog = true">
              <el-icon><DataLine /></el-icon>
              事务查询
            </el-button>
            <el-button type="warning" @click="showBatchRollbackDialog = true">
              <el-icon><RefreshLeft /></el-icon>
              批量回滚
            </el-button>
            <el-button type="success" @click="showSqlDialog = true">
              <el-icon><DocumentAdd /></el-icon>
              SQL执行
            </el-button>
            <el-button type="info" @click="showConnectionDialog = true">
              <el-icon><Connection /></el-icon>
              连接测试
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- StarRocks任务管理卡片 -->
      <el-card class="feature-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <div class="card-header-title">
              <el-icon class="card-icon"><Operation /></el-icon>
              <span>StarRocks任务管理</span>
            </div>
            <el-tag type="primary" size="small">可用</el-tag>
          </div>
        </template>
        
        <div class="card-content">
          <p class="card-description">
            查询和停止StarRocks异步任务，管理长时间运行的查询
          </p>
          
          <div class="feature-list">
            <div class="feature-item">
              <el-icon color="#67C23A"><Check /></el-icon>
              <span>任务查询</span>
            </div>
            <div class="feature-item">
              <el-icon color="#67C23A"><Check /></el-icon>
              <span>任务停止</span>
            </div>
            <div class="feature-item">
              <el-icon color="#67C23A"><Check /></el-icon>
              <span>任务监控</span>
            </div>
            <div class="feature-item">
              <el-icon color="#67C23A"><Check /></el-icon>
              <span>历史记录</span>
            </div>
          </div>
          
          <div class="card-actions">
            <el-button type="primary" @click="showTaskDialog = true">
              <el-icon><Search /></el-icon>
              查询任务
            </el-button>
            <el-button type="warning" @click="showStopTaskDialog = true">
              <el-icon><VideoPause /></el-icon>
              停止任务
            </el-button>
            <el-button type="danger" @click="showClearTaskDialog = true">
              <el-icon><Delete /></el-icon>
              清空任务
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 任务查询对话框 -->
    <el-dialog
      v-model="showTaskDialog"
      :width="taskDialogFullscreen ? '100%' : '80%'"
      :fullscreen="taskDialogFullscreen"
      :close-on-click-modal="false"
      class="unified-dialog task-query-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <div class="header-icon header-icon-primary">
            <el-icon><Search /></el-icon>
          </div>
          <div class="header-content">
            <h3>StarRocks任务查询</h3>
            <p>查询和监控StarRocks异步任务状态</p>
          </div>
          <el-button
            class="fullscreen-btn"
            :icon="FullScreen"
            circle
            @click="taskDialogFullscreen = !taskDialogFullscreen"
            :title="taskDialogFullscreen ? '退出全屏' : '全屏'"
          >
          </el-button>
        </div>
      </template>
      <div class="task-query-content">
        <!-- 环境选择 -->
        <el-form :model="taskForm" label-width="120px" class="task-form">
          <el-form-item label="StarRocks环境:">
            <el-select 
              v-model="taskForm.configId" 
              placeholder="请选择StarRocks环境"
              style="width: 300px"
              @change="loadTasks"
            >
              <el-option
                v-for="config in starRocksConfigs"
                :key="config.id"
                :label="config.config_name"
                :value="config.id"
              />
            </el-select>
          </el-form-item>
        </el-form>

        <!-- 筛选和排序控制 -->
        <div v-if="taskForm.configId" class="filter-controls">
          <el-form :model="filterForm" inline>
            <el-form-item label="状态筛选:">
              <el-select 
                v-model="filterForm.state" 
                placeholder="选择状态"
                style="width: 120px"
                @change="loadTasks"
              >
                <el-option label="全部" value="ALL" />
                <el-option label="运行中" value="RUNNING" />
                <el-option label="成功" value="SUCCESS" />
                <el-option label="失败" value="FAILED" />
                <el-option label="待执行" value="PENDING" />
                <el-option label="已提交" value="SUBMITTED" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="排序字段:">
              <el-select 
                v-model="filterForm.sortBy" 
                placeholder="选择排序字段"
                style="width: 140px"
                @change="loadTasks"
              >
                <el-option label="创建时间" value="CREATE_TIME" />
                <el-option label="完成时间" value="FINISH_TIME" />
                <el-option label="任务名称" value="TASK_NAME" />
                <el-option label="状态" value="STATE" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="排序方式:">
              <el-select 
                v-model="filterForm.sortOrder" 
                placeholder="排序方式"
                style="width: 100px"
                @change="loadTasks"
              >
                <el-option label="降序" value="DESC" />
                <el-option label="升序" value="ASC" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>

        <!-- 任务列表 -->
        <div v-if="taskForm.configId" class="tasks-container">
          <div class="tasks-header">
            <div class="tasks-title">
              <h4>StarRocks任务列表</h4>
              <div class="task-stats" v-if="taskStats">
                <el-tag 
                  v-for="(count, state) in taskStats.status_counts" 
                  :key="state"
                  :type="getTaskStateType(state)"
                  size="small"
                  style="margin-left: 8px"
                >
                  {{ translateTaskState(state) }}: {{ count }}
                </el-tag>
              </div>
            </div>
            <el-button 
              type="primary" 
              size="small" 
              @click="loadTasks"
              :loading="tasksLoading"
            >
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
          
          <el-table 
            :data="tasks" 
            v-loading="tasksLoading"
            style="width: 100%"
            empty-text="暂无任务"
            :default-sort="{prop: 'create_time', order: 'descending'}"
            :height="taskDialogFullscreen ? 'calc(100vh - 300px)' : '400'"
            class="tasks-table"
          >
            <el-table-column prop="task_name" label="任务名称" width="200" show-overflow-tooltip />
            <el-table-column prop="query_id" label="查询ID" width="150" show-overflow-tooltip />
            <el-table-column prop="state" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getTaskStateType(scope.row.state)">
                  {{ translateTaskState(scope.row.state) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="create_time" label="创建时间" width="180" />
            <el-table-column prop="finish_time" label="完成时间" width="180">
              <template #default="scope">
                {{ scope.row.finish_time || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="duration_ms" label="运行时长" width="120">
              <template #default="scope">
                {{ formatDuration(scope.row.duration_ms) }}
              </template>
            </el-table-column>
            <el-table-column prop="progress" label="进度" width="100">
              <template #default="scope">
                {{ scope.row.progress || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="catalog" label="目录" width="120" />
            <el-table-column prop="database" label="数据库" width="120" />
            <el-table-column prop="error_code" label="错误码" width="100">
              <template #default="scope">
                {{ scope.row.error_code || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="error_message" label="错误信息" width="200" show-overflow-tooltip>
              <template #default="scope">
                {{ scope.row.error_message || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="extra_message" label="额外信息" width="200" show-overflow-tooltip>
              <template #default="scope">
                {{ scope.row.extra_message || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="definition" label="任务定义" min-width="300" show-overflow-tooltip />
            <el-table-column label="操作" width="200" fixed="right" align="center">
              <template #default="scope">
                <div class="action-buttons">
                  <el-button 
                    type="primary" 
                    size="small"
                    @click="showTaskDetail(scope.row)"
                    :icon="View"
                    plain
                  >
                    详情
                  </el-button>
                  <el-button 
                    v-if="scope.row.can_delete"
                    type="danger" 
                    size="small"
                    @click="stopTask(scope.row.task_name)"
                    :loading="stoppingTasks.includes(scope.row.task_name)"
                    :icon="Delete"
                    plain
                  >
                    删除
                  </el-button>
                  <el-tag v-else type="info" size="small">只读</el-tag>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="closeTaskDialog">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 删除任务对话框 -->
    <el-dialog
      v-model="showStopTaskDialog"
      width="500px"
      :close-on-click-modal="false"
      class="unified-dialog stop-task-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <div class="header-icon header-icon-danger">
            <el-icon><VideoPause /></el-icon>
          </div>
          <div class="header-content">
            <h3>停止StarRocks任务</h3>
            <p>使用 DROP TASK 命令删除任务并取消TaskRun</p>
          </div>
        </div>
      </template>
      
      <el-form :model="stopTaskForm" label-width="120px">
        <el-form-item label="StarRocks环境:">
          <el-select 
            v-model="stopTaskForm.configId" 
            placeholder="请选择StarRocks环境"
            style="width: 100%"
          >
            <el-option
              v-for="config in starRocksConfigs"
              :key="config.id"
              :label="config.config_name"
              :value="config.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="任务名称:">
          <el-autocomplete
            v-model="stopTaskForm.taskName"
            :fetch-suggestions="searchTaskNames"
            placeholder="输入任务名称进行搜索"
            style="width: 100%"
            :debounce="300"
            @select="handleTaskNameSelect"
          >
            <template #default="{ item }">
              <div class="task-name-item">
                <el-icon><Operation /></el-icon>
                <span>{{ item.value }}</span>
              </div>
            </template>
          </el-autocomplete>
          <div style="font-size: 12px; color: #909399; margin-top: 4px;">
            支持模糊搜索，从数据库中查询任务名称
          </div>
        </el-form-item>
        
        <el-form-item label="强制删除:">
          <el-switch 
            v-model="stopTaskForm.force"
            active-text="是"
            inactive-text="否"
          />
          <div style="font-size: 12px; color: #909399; margin-top: 4px;">
            强制删除将添加 FORCE 参数
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showStopTaskDialog = false">取消</el-button>
        <el-button 
          type="danger" 
          @click="stopTaskById"
          :loading="stopTaskLoading"
          :disabled="!stopTaskForm.configId || !stopTaskForm.taskName"
        >
          删除任务
        </el-button>
      </template>
    </el-dialog>

    <!-- 清空任务对话框 -->
    <el-dialog
      v-model="showClearTaskDialog"
      width="600px"
      :close-on-click-modal="false"
      class="unified-dialog clear-task-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <div class="header-icon header-icon-danger">
            <el-icon><Delete /></el-icon>
          </div>
          <div class="header-content">
            <h3>清空StarRocks任务</h3>
            <p>删除该环境下所有的异步任务记录，此操作不可撤销</p>
          </div>
        </div>
      </template>
      
      <el-form :model="clearTaskForm" label-width="140px">
        <el-form-item label="StarRocks环境:" required>
          <el-select 
            v-model="clearTaskForm.configId" 
            placeholder="请选择要清空任务的StarRocks环境"
            style="width: 100%"
            @change="handleClearEnvChange"
          >
            <el-option
              v-for="config in starRocksConfigs"
              :key="config.id"
              :label="`${config.config_name} (${config.host}:${config.port})`"
              :value="config.id"
            >
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <span>{{ config.config_name }}</span>
                <span style="color: #909399; font-size: 12px;">
                  {{ config.host }}:{{ config.port }}
                </span>
              </div>
            </el-option>
          </el-select>
          <div style="font-size: 12px; color: #909399; margin-top: 4px;">
            选择需要清空任务的环境，将显示该环境的当前任务统计
          </div>
        </el-form-item>
        
        <!-- 当前环境任务统计 -->
        <el-form-item label="当前任务总数:" v-if="clearTaskForm.configId">
          <div v-if="clearTaskStatsLoading" style="text-align: center; padding: 20px;">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span style="margin-left: 8px;">正在加载任务统计...</span>
          </div>
          <div v-else-if="clearTaskStats" class="clear-task-stats">
            <div class="stats-item">
              <span class="stats-value total">{{ clearTaskStats.total_count || 0 }}</span>
              <span class="stats-label">个任务</span>
            </div>
          </div>
          <div v-else style="color: #909399; font-size: 13px;">
            未能获取任务统计信息
          </div>
        </el-form-item>
        
        <el-form-item label="二次确认:" required>
          <el-input 
            v-model="clearTaskForm.confirmation"
            placeholder='请输入 "确认清空" 以继续'
            style="width: 100%"
          />
          <div style="font-size: 12px; color: #F56C6C; margin-top: 4px;">
            请输入"确认清空"（不含引号）以确认此危险操作
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="handleCancelClear">取消</el-button>
        <el-button 
          type="danger" 
          @click="handleConfirmClear"
          :loading="clearTaskLoading"
          :disabled="!clearTaskForm.configId || clearTaskForm.confirmation !== '确认清空'"
        >
          确认清空
        </el-button>
      </template>
    </el-dialog>

    <!-- 事务查询对话框 -->
    <el-dialog
      v-model="showTransactionDialog"
      :width="transactionDialogFullscreen ? '100%' : '90%'"
      :fullscreen="transactionDialogFullscreen"
      :close-on-click-modal="false"
      class="unified-dialog transaction-query-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <div class="header-icon header-icon-primary">
            <el-icon><Coin /></el-icon>
          </div>
          <div class="header-content">
            <h3>StarRocks事务查询与管理</h3>
            <p>查询运行中的事务状态，执行批量回滚操作</p>
          </div>
          <el-button
            class="fullscreen-btn"
            :icon="FullScreen"
            circle
            @click="transactionDialogFullscreen = !transactionDialogFullscreen"
            :title="transactionDialogFullscreen ? '退出全屏' : '全屏'"
          >
          </el-button>
        </div>
      </template>
      <!-- 配置选择和查询条件 -->
      <div class="transaction-query-form">
        <el-form :model="transactionForm" inline size="default">
          <el-form-item label="StarRocks配置">
            <el-select
              v-model="transactionForm.configId"
              placeholder="请选择配置"
              @change="handleConfigChange"
              style="width: 200px"
            >
              <el-option
                v-for="config in starRocksConfigs"
                :key="config.id"
                :label="`${config.config_name || config.name || 'StarRocks'} (${config.host || config.hostname}:${config.port})`"
                :value="config.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="数据库">
            <el-select
              v-model="transactionForm.database"
              placeholder="请选择数据库"
              style="width: 150px"
              filterable
              :loading="databasesLoading"
            >
              <el-option
                v-for="db in databases"
                :key="db.schema_name"
                :label="db.schema_name"
                :value="db.schema_name"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="时间过滤">
            <el-select
              v-model="transactionForm.timeCondition"
              placeholder="选择时间条件"
              style="width: 200px"
              clearable
            >
              <el-option label="所有事务" value="" />
              <el-option label="今天的事务" value="today" />
              <el-option label="昨天的事务" value="yesterday" />
              <el-option label="过去1小时" value="last_hour" />
              <el-option label="过去2小时" value="last_2_hours" />
              <el-option label="过去6小时" value="last_6_hours" />
              <el-option label="过去12小时" value="last_12_hours" />
              <el-option label="过去24小时" value="last_24_hours" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button 
              type="primary" 
              @click="queryTransactions"
              :loading="transactionLoading"
              :disabled="!transactionForm.configId || !transactionForm.database"
            >
              <el-icon><Search /></el-icon>
              查询事务
            </el-button>
          </el-form-item>

          <el-form-item>
            <el-button 
              type="warning" 
              @click="batchRollbackSelected"
              :loading="rollbackLoading"
              :disabled="selectedTransactions.length === 0"
            >
              <el-icon><RefreshLeft /></el-icon>
              批量回滚选中
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 事务列表 -->
      <el-table
        :data="transactions"
        v-loading="transactionLoading"
        :height="transactionDialogFullscreen ? 'calc(100vh - 300px)' : '400'"
        class="transactions-table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="Label" label="Label" width="200" show-overflow-tooltip />
        <el-table-column prop="TransactionId" label="事务ID" width="120" />
        <el-table-column prop="TransactionStatus" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getTransactionStateType(scope.row.TransactionStatus)">
              {{ scope.row.TransactionStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="PrepareTime" label="准备时间" width="180" />
        <el-table-column prop="Coordinator" label="协调器" width="120" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button
              type="danger"
              size="small"
              @click="rollbackSingleTransaction(scope.row)"
              :loading="rollbackLoading"
            >
              回滚
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 统计信息 -->
      <div class="transaction-stats" v-if="transactions.length > 0">
        <el-text type="info">
          共查询到 {{ transactions.length }} 个事务，已选中 {{ selectedTransactions.length }} 个
        </el-text>
      </div>
      
      <template #footer>
        <el-button @click="closeTransactionDialog">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 批量回滚确认对话框 -->
    <el-dialog
      v-model="showBatchRollbackDialog"
      width="600px"
      :close-on-click-modal="false"
      class="unified-dialog batch-rollback-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <div class="header-icon header-icon-warning">
            <el-icon><RefreshLeft /></el-icon>
          </div>
          <div class="header-content">
            <h3>批量回滚确认</h3>
            <p>回滚所有选中的事务，请确认配置信息无误后执行</p>
          </div>
        </div>
      </template>
      <div class="batch-rollback-form">
        
        <el-form :model="batchRollbackForm" label-width="120px" style="margin-top: 20px;">
          <el-form-item label="StarRocks配置">
            <el-select
              v-model="batchRollbackForm.configId"
              placeholder="请选择配置"
              style="width: 100%"
            >
              <el-option
                v-for="config in starRocksConfigs"
                :key="config.id"
                :label="`${config.config_name || config.name || 'StarRocks'} (${config.host || config.hostname}:${config.port})`"
                :value="config.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="数据库">
            <el-select
              v-model="batchRollbackForm.database"
              placeholder="请选择数据库"
              style="width: 100%"
              filterable
              :loading="databasesLoading"
            >
              <el-option
                v-for="db in databases"
                :key="db.schema_name"
                :label="db.schema_name"
                :value="db.schema_name"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="任务间隔">
            <el-input-number
              v-model="batchRollbackForm.sleepInterval"
              :min="0"
              :max="60"
              placeholder="秒"
            />
            <el-text type="info" style="margin-left: 10px;">设置任务间的等待时间（秒）</el-text>
          </el-form-item>

          <el-form-item label="Labels">
            <el-input
              v-model="batchRollbackForm.labelsText"
              type="textarea"
              :rows="6"
              placeholder="请输入要回滚的Label，每行一个"
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="showBatchRollbackDialog = false">取消</el-button>
        <el-button 
          type="danger" 
          @click="executeBatchRollback"
          :loading="rollbackLoading"
          :disabled="!batchRollbackForm.configId || !batchRollbackForm.database || !batchRollbackForm.labelsText.trim()"
        >
          确认回滚
        </el-button>
      </template>
    </el-dialog>

    <!-- SQL执行对话框 -->
    <el-dialog
      v-model="showSqlDialog"
      width="70%"
      :close-on-click-modal="false"
      class="unified-dialog sql-execute-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <div class="header-icon header-icon-success">
            <el-icon><DocumentAdd /></el-icon>
          </div>
          <div class="header-content">
            <h3>SQL执行</h3>
            <p>执行自定义SQL语句并查看结果</p>
          </div>
        </div>
      </template>
      <el-form :model="sqlForm" label-width="120px">
        <el-form-item label="StarRocks配置">
          <el-select
            v-model="sqlForm.configId"
            placeholder="请选择配置"
            style="width: 100%"
            @change="handleSqlConfigChange"
          >
            <el-option
              v-for="config in starRocksConfigs"
              :key="config.id"
              :label="`${config.config_name || config.name || 'StarRocks'} (${config.host || config.hostname}:${config.port})`"
              :value="config.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="数据库">
          <el-select
            v-model="sqlForm.database"
            placeholder="请选择数据库（可选）"
            style="width: 100%"
            clearable
            :loading="databasesLoading"
          >
            <el-option
              v-for="db in databases"
              :key="db.schema_name"
              :label="db.schema_name"
              :value="db.schema_name"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="SQL语句">
          <el-input
            v-model="sqlForm.sql"
            type="textarea"
            :rows="8"
            placeholder="请输入SQL查询语句（只支持SELECT查询）"
          />
        </el-form-item>
      </el-form>

      <!-- 执行结果 -->
      <div v-if="sqlResult" class="sql-result">
        <el-divider content-position="left">执行结果</el-divider>
        <el-table :data="sqlResult" max-height="300" stripe>
          <el-table-column
            v-for="(value, key) in sqlResult[0] || {}"
            :key="key"
            :prop="key"
            :label="key"
            show-overflow-tooltip
          />
        </el-table>
      </div>

      <template #footer>
        <el-button @click="showSqlDialog = false">关闭</el-button>
        <el-button 
          type="primary" 
          @click="executeSql"
          :loading="sqlLoading"
          :disabled="!sqlForm.configId || !sqlForm.sql.trim()"
        >
          执行查询
        </el-button>
      </template>
    </el-dialog>

    <!-- 连接测试对话框 -->
    <el-dialog
      v-model="showConnectionDialog"
      width="500px"
      :close-on-click-modal="false"
      class="unified-dialog connection-test-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <div class="header-icon header-icon-info">
            <el-icon><Connection /></el-icon>
          </div>
          <div class="header-content">
            <h3>连接测试</h3>
            <p>测试StarRocks数据库连接状态</p>
          </div>
        </div>
      </template>
      <el-form :model="connectionForm" label-width="120px">
        <el-form-item label="StarRocks配置">
          <el-select
            v-model="connectionForm.configId"
            placeholder="请选择配置"
            style="width: 100%"
          >
            <el-option
              v-for="config in starRocksConfigs"
              :key="config.id"
              :label="`${config.config_name || config.name || 'StarRocks'} (${config.host || config.hostname}:${config.port})`"
              :value="config.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 测试结果 -->
      <div v-if="connectionResult" class="connection-result">
        <el-divider content-position="left">测试结果</el-divider>
        <el-alert
          :title="connectionResult.success ? '连接成功' : '连接失败'"
          :type="connectionResult.success ? 'success' : 'error'"
          :description="connectionResult.message"
          show-icon
          :closable="false"
        />
      </div>

      <template #footer>
        <el-button @click="showConnectionDialog = false">关闭</el-button>
        <el-button 
          type="primary" 
          @click="testConnection"
          :loading="connectionLoading"
          :disabled="!connectionForm.configId"
        >
          测试连接
        </el-button>
      </template>
    </el-dialog>

    <!-- 任务详情对话框 -->
    <el-dialog
      v-model="showTaskDetailDialog"
      width="900px"
      :close-on-click-modal="false"
      class="unified-dialog task-detail-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <div class="header-icon header-icon-primary">
            <el-icon><DocumentAdd /></el-icon>
          </div>
          <div class="header-content">
            <h3>任务详情</h3>
            <p>查看任务的完整定义和详细信息</p>
          </div>
        </div>
      </template>

      <div v-if="selectedTaskDetail" class="task-detail-content">
        <!-- 基本信息 -->
        <el-descriptions :column="2" border class="task-detail-descriptions">
          <el-descriptions-item label="任务名称">
            <el-tag type="primary">{{ selectedTaskDetail.task_name }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="查询ID">
            {{ selectedTaskDetail.query_id }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getTaskStateType(selectedTaskDetail.state)">
              {{ translateTaskState(selectedTaskDetail.state) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="运行时长">
            {{ formatDuration(selectedTaskDetail.duration_ms) }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ selectedTaskDetail.create_time }}
          </el-descriptions-item>
          <el-descriptions-item label="完成时间">
            {{ selectedTaskDetail.finish_time || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="目录">
            {{ selectedTaskDetail.catalog }}
          </el-descriptions-item>
          <el-descriptions-item label="数据库">
            {{ selectedTaskDetail.database }}
          </el-descriptions-item>
          <el-descriptions-item label="进度" v-if="selectedTaskDetail.progress">
            {{ selectedTaskDetail.progress }}
          </el-descriptions-item>
          <el-descriptions-item label="错误码" v-if="selectedTaskDetail.error_code">
            <el-tag type="danger">{{ selectedTaskDetail.error_code }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="错误信息" :span="2" v-if="selectedTaskDetail.error_message">
            <el-text type="danger">{{ selectedTaskDetail.error_message }}</el-text>
          </el-descriptions-item>
          <el-descriptions-item label="额外信息" :span="2" v-if="selectedTaskDetail.extra_message">
            {{ selectedTaskDetail.extra_message }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- SQL定义 -->
        <el-divider content-position="left">
          <el-icon><DocumentAdd /></el-icon>
          <span style="margin-left: 8px;">任务定义（SQL）</span>
        </el-divider>
        <div class="sql-definition-container">
          <div class="sql-definition-header">
            <el-text type="info" size="small">完整的任务定义SQL语句</el-text>
            <div class="sql-actions">
              <el-button 
                type="success" 
                size="small" 
                @click="toggleSqlFormat"
                :icon="isSqlFormatted ? RefreshLeft : Check"
              >
                {{ isSqlFormatted ? '恢复原样' : '美化SQL' }}
              </el-button>
              <el-button 
                type="primary" 
                size="small" 
                @click="copySqlToClipboard"
                :icon="CopyDocument"
              >
                复制SQL
              </el-button>
            </div>
          </div>
          <el-input
            v-model="displayedSql"
            type="textarea"
            :rows="12"
            readonly
            class="sql-textarea"
          />
        </div>
      </div>

      <template #footer>
        <el-button @click="showTaskDetailDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  DataLine, 
  ArrowLeft, 
  Check, 
  RefreshLeft, 
  DocumentAdd, 
  Connection, 
  Operation, 
  Search, 
  VideoPause, 
  Refresh,
  Delete,
  Loading,
  Document,
  Coin,
  CopyDocument,
  View,
  FullScreen
} from '@element-plus/icons-vue'
import api from '@/utils/api'
import { formatDurationFromMilliseconds } from '@/utils/duration'
import { componentLogger } from '@/utils/logger'
import { copyToClipboard as copyText } from '@/utils/clipboard'

// 响应式数据
const showTaskDialog = ref(false)
const taskDialogFullscreen = ref(false)
const showStopTaskDialog = ref(false)
const showClearTaskDialog = ref(false)
const showTaskDetailDialog = ref(false)
const selectedTaskDetail = ref(null)
const transactionDialogFullscreen = ref(false)
const isSqlFormatted = ref(false)
const displayedSql = ref('')
const starRocksConfigs = ref([])
const tasks = ref([])
const tasksLoading = ref(false)
const stopTaskLoading = ref(false)
const clearTaskLoading = ref(false)
const clearTaskStatsLoading = ref(false)
const stoppingTasks = ref([])
const taskStats = ref(null)
const clearTaskStats = ref(null)

// 表单数据
const taskForm = ref({
  configId: null
})

const stopTaskForm = ref({
  configId: null,
  taskName: '',
  force: false
})

const clearTaskForm = ref({
  configId: null,
  confirmation: ''
})

// 筛选表单数据
const filterForm = ref({
  state: 'ALL',
  sortBy: 'CREATE_TIME',
  sortOrder: 'DESC'
})

// 事务管理相关数据
const showTransactionDialog = ref(false)
const showBatchRollbackDialog = ref(false)
const showSqlDialog = ref(false)
const showConnectionDialog = ref(false)
const transactions = ref([])
const selectedTransactions = ref([])
const transactionLoading = ref(false)
const rollbackLoading = ref(false)
const databases = ref([])
const databasesLoading = ref(false)

// 事务查询表单
const transactionForm = ref({
  configId: null,
  database: '',
  timeCondition: ''
})

// 批量回滚表单
const batchRollbackForm = ref({
  configId: null,
  database: '',
  sleepInterval: 10,
  labelsText: ''
})

// SQL执行相关
const sqlForm = ref({
  configId: null,
  database: '',
  sql: ''
})
const sqlResult = ref(null)
const sqlLoading = ref(false)

// 连接测试相关
const connectionForm = ref({
  configId: null
})
const connectionResult = ref(null)
const connectionLoading = ref(false)

// 方法
const loadStarRocksConfigs = async () => {
  try {
    const response = await api.get('/starrocks/configs')
    if (response.data.success) {
      starRocksConfigs.value = response.data.data
      componentLogger.info(`加载到 ${starRocksConfigs.value.length} 个StarRocks配置`)
    } else {
      ElMessage.error('加载StarRocks配置失败: ' + response.data.message)
    }
  } catch (error) {
    componentLogger.error('加载StarRocks配置异常', error)
    ElMessage.error('加载StarRocks配置异常: ' + error.message)
  }
}

// 关闭任务查询对话框
const closeTaskDialog = () => {
  showTaskDialog.value = false
  taskDialogFullscreen.value = false  // 重置全屏状态
}

// 关闭事务查询对话框
const closeTransactionDialog = () => {
  showTransactionDialog.value = false
  transactionDialogFullscreen.value = false  // 重置全屏状态
}

const loadTasks = async () => {
  if (!taskForm.value.configId) return
  
  try {
    tasksLoading.value = true
    const response = await api.get('/starrocks/tasks', {
      params: { 
        config_id: taskForm.value.configId,
        state: filterForm.value.state,
        sort_by: filterForm.value.sortBy,
        sort_order: filterForm.value.sortOrder
      }
    })
    
    if (response.data.success) {
      const data = response.data.data
      tasks.value = data.tasks || []
      taskStats.value = {
        total_count: data.total_count || 0,
        status_counts: data.status_counts || {},
        filters: data.filters || {}
      }
      componentLogger.info(`加载到 ${tasks.value.length} 个任务`)
      ElMessage.success(`查询到 ${tasks.value.length} 个任务`)
    } else {
      ElMessage.error('查询任务失败: ' + response.data.message)
      tasks.value = []
      taskStats.value = null
    }
  } catch (error) {
    componentLogger.error('查询任务异常', error)
    ElMessage.error('查询任务异常: ' + error.message)
    tasks.value = []
    taskStats.value = null
  } finally {
    tasksLoading.value = false
  }
}

const stopTask = async (taskName) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除任务 "${taskName}" 吗？此操作将使用 DROP TASK 命令，不可撤销！`,
      '确认删除任务',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    stoppingTasks.value.push(taskName)
    
    const response = await api.post('/starrocks/stop-task', {
      config_id: taskForm.value.configId,
      task_name: taskName,
      force: false
    })
    
    if (response.data.success) {
      ElMessage.success('任务删除成功')
      // 重新加载任务列表
      await loadTasks()
    } else {
      ElMessage.error('删除任务失败: ' + response.data.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      componentLogger.error('删除任务异常', error)
      ElMessage.error('删除任务异常: ' + error.message)
    }
  } finally {
    stoppingTasks.value = stoppingTasks.value.filter(name => name !== taskName)
  }
}

const stopTaskById = async () => {
  try {
    stopTaskLoading.value = true
    
    const response = await api.post('/starrocks/stop-task', {
      config_id: stopTaskForm.value.configId,
      task_name: stopTaskForm.value.taskName,
      force: stopTaskForm.value.force
    })
    
    if (response.data.success) {
      ElMessage.success('任务删除成功')
      showStopTaskDialog.value = false
      // 清空表单
      stopTaskForm.value.taskName = ''
      stopTaskForm.value.force = false
      // 重新加载任务列表
      if (taskForm.value.configId === stopTaskForm.value.configId) {
        await loadTasks()
      }
    } else {
      ElMessage.error('删除任务失败: ' + response.data.message)
    }
  } catch (error) {
    componentLogger.error('删除任务异常', error)
    ElMessage.error('删除任务异常: ' + error.message)
  } finally {
    stopTaskLoading.value = false
  }
}

// 清空任务相关方法
const handleClearEnvChange = async () => {
  // 切换环境时清空统计数据和确认输入
  clearTaskStats.value = null
  clearTaskForm.value.confirmation = ''
  
  if (!clearTaskForm.value.configId) return
  
  try {
    clearTaskStatsLoading.value = true
    // 调用专门的统计API（不带LIMIT限制，只返回总数）
    const response = await api.get('/starrocks/tasks/stats', {
      params: { 
        config_id: clearTaskForm.value.configId
      }
    })
    
    if (response.data.success) {
      const data = response.data.data
      clearTaskStats.value = {
        total_count: data.total_count || 0
      }
    }
  } catch (error) {
    componentLogger.error('加载任务统计失败', error)
    ElMessage.warning('无法加载任务统计信息')
  } finally {
    clearTaskStatsLoading.value = false
  }
}

const handleCancelClear = () => {
  showClearTaskDialog.value = false
  // 清空表单
  clearTaskForm.value.configId = null
  clearTaskForm.value.confirmation = ''
  clearTaskStats.value = null
}

const handleConfirmClear = async () => {
  if (clearTaskForm.value.confirmation !== '确认清空') {
    ElMessage.warning('请输入"确认清空"以确认操作')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要清空该环境下的所有任务吗？共 ${clearTaskStats.value?.total_count || 0} 个任务。此操作不可撤销！`,
      '最终确认',
      {
        confirmButtonText: '确认清空',
        cancelButtonText: '取消',
        type: 'error',
        dangerouslyUseHTMLString: true
      }
    )
    
    clearTaskLoading.value = true
    
    // 调用后端API清空任务
    const response = await api.post('/starrocks/clear-tasks', {
      config_id: clearTaskForm.value.configId
    })
    
    if (response.data.success) {
      ElMessage.success(response.data.message || '成功清空所有任务')
      handleCancelClear()
      // 重新加载任务列表
      if (taskForm.value.configId === clearTaskForm.value.configId) {
        await loadTasks()
      }
    } else {
      ElMessage.error('清空任务失败: ' + response.data.message)
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      componentLogger.error('清空任务异常', error)
      ElMessage.error('清空任务异常: ' + (error.response?.data?.message || error.message))
    }
  } finally {
    clearTaskLoading.value = false
  }
}

// 搜索任务名称
const searchTaskNames = async (queryString, callback) => {
  if (!stopTaskForm.value.configId) {
    callback([])
    return
  }
  
  try {
    const response = await api.get('/starrocks/task-names', {
      params: {
        config_id: stopTaskForm.value.configId,
        search: queryString
      }
    })
    
    if (response.data.success) {
      const suggestions = response.data.data.task_names.map(name => ({
        value: name
      }))
      callback(suggestions)
    } else {
      callback([])
    }
  } catch (error) {
    componentLogger.error('搜索任务名称失败', error)
    callback([])
  }
}

// 选择任务名称
const handleTaskNameSelect = (item) => {
  stopTaskForm.value.taskName = item.value
}

// 格式化时长显示 - 使用通用工具函数
const formatDuration = (durationMs) => {
  return formatDurationFromMilliseconds(durationMs, { language: 'en' })
}

const getTaskStateType = (state) => {
  const stateMap = {
    'RUNNING': 'primary',
    'PENDING': 'warning',
    'FINISHED': 'success',
    'SUCCESS': 'success',
    'CANCELLED': 'info',
    'FAILED': 'danger',
    'SUBMITTED': 'info'
  }
  return stateMap[state] || 'default'
}

// 翻译任务状态为中文
const translateTaskState = (state) => {
  const stateTranslations = {
    'RUNNING': '运行中',
    'PENDING': '待执行',
    'FINISHED': '已完成',
    'SUCCESS': '成功',
    'CANCELLED': '已取消',
    'FAILED': '失败',
    'SUBMITTED': '已提交'
  }
  return stateTranslations[state] || state
}

// 事务管理方法
const queryTransactions = async () => {
  if (!transactionForm.value.configId || !transactionForm.value.database) {
    ElMessage.error('请选择StarRocks配置并输入数据库名')
    return
  }

  try {
    transactionLoading.value = true
    
    // 使用过滤API来获取事务
    const response = await api.post('/starrocks/transactions/filter', {
      config_id: transactionForm.value.configId,
      database: transactionForm.value.database,
      time_condition: transactionForm.value.timeCondition,
      use_show_proc: true // 使用SHOW PROC方式兼容脚本
    })

    if (response.data.success) {
      transactions.value = response.data.data.transactions || []
      ElMessage.success(`查询成功，找到 ${transactions.value.length} 个事务`)
    } else {
      ElMessage.error('查询事务失败: ' + response.data.message)
    }
  } catch (error) {
    componentLogger.error('查询事务异常', error)
    ElMessage.error('查询事务异常: ' + error.message)
  } finally {
    transactionLoading.value = false
  }
}

const handleSelectionChange = (selection) => {
  selectedTransactions.value = selection
}

const handleConfigChange = async () => {
  // 配置改变时清空已查询的事务
  transactions.value = []
  selectedTransactions.value = []
  
  // 加载新配置的数据库列表
  if (transactionForm.value.configId) {
    await loadDatabases(transactionForm.value.configId)
  }
}

// 加载数据库列表
const loadDatabases = async (configId) => {
  if (!configId) return
  
  try {
    databasesLoading.value = true
    const response = await api.get('/starrocks/databases', {
      params: { config_id: configId }
    })

    if (response.data.success) {
      databases.value = response.data.data || []
      componentLogger.info(`加载到 ${databases.value.length} 个数据库`)
    } else {
      ElMessage.error('加载数据库列表失败: ' + response.data.message)
    }
  } catch (error) {
    componentLogger.error('加载数据库列表异常', error)
    ElMessage.error('加载数据库列表异常: ' + error.message)
  } finally {
    databasesLoading.value = false
  }
}

// SQL配置变化处理
const handleSqlConfigChange = async () => {
  // 配置改变时清空数据库选择
  sqlForm.value.database = ''
  
  // 加载新配置的数据库列表
  if (sqlForm.value.configId) {
    await loadDatabases(sqlForm.value.configId)
  }
}

const getTransactionStateType = (state) => {
  const stateMap = {
    'RUNNING': 'primary',
    'PREPARE': 'warning',
    'PREPARED': 'warning',
    'PRECOMMITTED': 'info',
    'COMMITTED': 'success',
    'VISIBLE': 'success',
    'ABORTED': 'danger',
    'UNKNOWN': 'info'
  }
  return stateMap[state] || 'default'
}

const rollbackSingleTransaction = async (transaction) => {
  try {
    await ElMessageBox.confirm(
      `确定要回滚事务 "${transaction.Label}" 吗？此操作不可撤销。`,
      '回滚确认',
      {
        confirmButtonText: '确定回滚',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    rollbackLoading.value = true
    
    const response = await api.post('/starrocks/transactions/rollback-by-label', {
      config_id: transactionForm.value.configId,
      label: transaction.Label,
      database: transactionForm.value.database
    })

    if (response.data.success) {
      ElMessage.success('事务回滚成功')
      // 重新查询事务列表
      await queryTransactions()
    } else {
      ElMessage.error('事务回滚失败: ' + response.data.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      componentLogger.error('回滚事务异常', error)
      ElMessage.error('回滚事务异常: ' + error.message)
    }
  } finally {
    rollbackLoading.value = false
  }
}

const batchRollbackSelected = async () => {
  if (selectedTransactions.value.length === 0) {
    ElMessage.warning('请选择要回滚的事务')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要回滚选中的 ${selectedTransactions.value.length} 个事务吗？此操作不可撤销。`,
      '批量回滚确认',
      {
        confirmButtonText: '确定回滚',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    rollbackLoading.value = true
    
    const labels = selectedTransactions.value.map(txn => txn.Label)
    
    const response = await api.post('/starrocks/transactions/batch-rollback-by-labels', {
      config_id: transactionForm.value.configId,
      labels: labels,
      database: transactionForm.value.database,
      sleep_interval: 2 // 任务间隔2秒
    })

    if (response.data.success) {
      const result = response.data.data
      ElMessage.success(`批量回滚完成: 成功 ${result.success_count} 个, 失败 ${result.failed_count} 个`)
      // 重新查询事务列表
      await queryTransactions()
    } else {
      ElMessage.error('批量回滚失败: ' + response.data.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      componentLogger.error('批量回滚异常', error)
      ElMessage.error('批量回滚异常: ' + error.message)
    }
  } finally {
    rollbackLoading.value = false
  }
}

const executeBatchRollback = async () => {
  if (!batchRollbackForm.value.labelsText.trim()) {
    ElMessage.warning('请输入要回滚的Labels')
    return
  }

  try {
    rollbackLoading.value = true
    
    // 解析Labels（每行一个）
    const labels = batchRollbackForm.value.labelsText
      .split('\n')
      .map(label => label.trim())
      .filter(label => label.length > 0)

    if (labels.length === 0) {
      ElMessage.warning('请输入有效的Labels')
      return
    }
    
    const response = await api.post('/starrocks/transactions/batch-rollback-by-labels', {
      config_id: batchRollbackForm.value.configId,
      labels: labels,
      database: batchRollbackForm.value.database,
      sleep_interval: batchRollbackForm.value.sleepInterval
    })

    if (response.data.success) {
      const result = response.data.data
      ElMessage.success(`批量回滚完成: 成功 ${result.success_count} 个, 失败 ${result.failed_count} 个`)
      showBatchRollbackDialog.value = false
      
      // 如果事务查询对话框开着，重新查询
      if (showTransactionDialog.value && transactionForm.value.configId && transactionForm.value.database) {
        await queryTransactions()
      }
    } else {
      ElMessage.error('批量回滚失败: ' + response.data.message)
    }
  } catch (error) {
    componentLogger.error('批量回滚异常', error)
    ElMessage.error('批量回滚异常: ' + error.message)
  } finally {
    rollbackLoading.value = false
  }
}

// SQL执行方法
const executeSql = async () => {
  try {
    sqlLoading.value = true
    sqlResult.value = null
    
    const response = await api.post('/starrocks/query', {
      config_id: sqlForm.value.configId,
      sql: sqlForm.value.sql,
      database: sqlForm.value.database
    })

    if (response.data.success) {
      sqlResult.value = response.data.data.results || []
      ElMessage.success('SQL执行成功')
    } else {
      ElMessage.error('SQL执行失败: ' + response.data.message)
    }
  } catch (error) {
    componentLogger.error('SQL执行异常', error)
    ElMessage.error('SQL执行异常: ' + error.message)
  } finally {
    sqlLoading.value = false
  }
}

// 连接测试方法
const testConnection = async () => {
  try {
    connectionLoading.value = true
    connectionResult.value = null
    
    const response = await api.post('/starrocks/test-connection', {
      config_id: connectionForm.value.configId
    })

    connectionResult.value = {
      success: response.data.success,
      message: response.data.message
    }
    
    if (response.data.success) {
      ElMessage.success('连接测试成功')
    } else {
      ElMessage.error('连接测试失败')
    }
  } catch (error) {
    connectionResult.value = {
      success: false,
      message: error.message
    }
    componentLogger.error('连接测试异常', error)
    ElMessage.error('连接测试异常: ' + error.message)
  } finally {
    connectionLoading.value = false
  }
}

// SQL美化函数
const formatSql = (sql) => {
  if (!sql) return ''
  
  // 基础SQL关键字
  const keywords = [
    'SELECT', 'FROM', 'WHERE', 'AND', 'OR', 'ORDER BY', 'GROUP BY', 'HAVING',
    'JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'INNER JOIN', 'OUTER JOIN',
    'INSERT INTO', 'UPDATE', 'DELETE', 'CREATE', 'DROP', 'ALTER',
    'UNION', 'UNION ALL', 'LIMIT', 'OFFSET', 'AS',
    'ON', 'USING', 'CASE', 'WHEN', 'THEN', 'ELSE', 'END',
    'DISTINCT', 'COUNT', 'SUM', 'AVG', 'MAX', 'MIN',
    'SCHEDULE', 'EVERY', 'STARTS', 'ENDS', 'COMMENT'
  ]
  
  let formatted = sql
  
  // 在主要关键字前添加换行和缩进
  const majorKeywords = ['SELECT', 'FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'HAVING', 'LIMIT', 'SCHEDULE', 'COMMENT']
  majorKeywords.forEach(keyword => {
    const regex = new RegExp(`\\s+(${keyword})\\s+`, 'gi')
    formatted = formatted.replace(regex, '\n$1 ')
  })
  
  // AND/OR 前换行并增加缩进
  formatted = formatted.replace(/\s+(AND|OR)\s+/gi, '\n  $1 ')
  
  // JOIN 前换行
  formatted = formatted.replace(/\s+((?:LEFT\s+|RIGHT\s+|INNER\s+|OUTER\s+)?JOIN)\s+/gi, '\n$1 ')
  
  // 逗号后添加换行（SELECT字段列表）
  formatted = formatted.replace(/,\s*(?=\w)/g, ',\n  ')
  
  // 清理多余的空白和换行
  formatted = formatted
    .split('\n')
    .map(line => line.trim())
    .filter(line => line.length > 0)
    .join('\n')
  
  // 简单的缩进逻辑
  const lines = formatted.split('\n')
  let indentLevel = 0
  const indentedLines = lines.map(line => {
    const trimmedLine = line.trim()
    
    // 减少缩进的关键字
    if (trimmedLine.match(/^(FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|SCHEDULE|COMMENT)/i)) {
      indentLevel = 1
    } else if (trimmedLine.match(/^(AND|OR)/i)) {
      indentLevel = 2
    } else if (trimmedLine.match(/^(SELECT|INSERT|UPDATE|DELETE|CREATE)/i)) {
      indentLevel = 0
    }
    
    const indent = '  '.repeat(indentLevel)
    return indent + trimmedLine
  })
  
  return indentedLines.join('\n')
}

// 切换SQL格式化状态
const toggleSqlFormat = () => {
  if (!selectedTaskDetail.value) return
  
  isSqlFormatted.value = !isSqlFormatted.value
  
  if (isSqlFormatted.value) {
    // 美化SQL
    displayedSql.value = formatSql(selectedTaskDetail.value.definition)
    ElMessage.success('SQL已美化')
  } else {
    // 恢复原样（界面已变化，不需要额外提示）
    displayedSql.value = selectedTaskDetail.value.definition
  }
}

// 显示任务详情
const showTaskDetail = (task) => {
  selectedTaskDetail.value = { ...task }
  isSqlFormatted.value = false  // 重置美化状态
  displayedSql.value = task.definition  // 默认显示原始SQL
  showTaskDetailDialog.value = true
  componentLogger.info(`查看任务详情: ${task.task_name}`)
}

// 复制SQL到剪贴板 - 使用统一工具
const copySqlToClipboard = async () => {
  if (!displayedSql.value) {
    ElMessage.warning('没有可复制的SQL内容')
    return
  }
  await copyText(displayedSql.value, 'SQL')
}

// 生命周期
onMounted(() => {
  loadStarRocksConfigs()
})
</script>

<style scoped>
.page-container {
  padding: 0;
  min-height: calc(100vh - 60px);
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.title-with-back {
  display: flex;
  align-items: flex-start;
  gap: 15px;
}

.blue-return-button {
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
  flex-shrink: 0;
  margin-top: 2px;
}

.blue-return-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.4);
  background: linear-gradient(135deg, #66b3ff 0%, #409eff 100%);
}

.title-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.title-main {
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-icon {
  font-size: 28px;
  color: #F56C6C;
  background: linear-gradient(135deg, #F56C6C 0%, #F78989 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-title h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-description {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  padding: 10px 16px;
  background: linear-gradient(135deg, #f5f7fa 0%, #ecf3fc 100%);
  border-left: 3px solid #F56C6C;
  border-radius: 6px;
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

.page-description .el-icon {
  font-size: 16px;
  color: #F56C6C;
  flex-shrink: 0;
}

.page-description span {
  flex: 1;
}

/* 卡片容器 */
.cards-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.feature-card {
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.feature-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  border-color: #409eff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-icon {
  font-size: 20px;
  color: #F56C6C;
  background: linear-gradient(135deg, #F56C6C 0%, #F78989 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.card-content {
  padding: 8px 0;
}

.card-description {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 20px;
}

.feature-list {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin-bottom: 24px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
}

.card-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.card-actions .el-button {
  border-radius: 8px;
  font-weight: 500;
}

/* 任务查询对话框样式 */
.task-query-content {
  padding: 8px 0;
}

.task-form {
  margin-bottom: 24px;
}

/* 筛选控制样式 */
.filter-controls {
  margin: 16px 0 24px 0;
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.filter-controls .el-form {
  margin: 0;
}

.filter-controls .el-form-item {
  margin-bottom: 0;
  margin-right: 24px;
}

.tasks-container {
  margin-top: 24px;
}

.tasks-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e4e7ed;
}

.tasks-title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.tasks-title h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.task-stats {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .cards-container {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .feature-list {
    grid-template-columns: 1fr;
  }
  
  .card-actions {
    flex-direction: column;
  }
  
  .card-actions .el-button {
    width: 100%;
  }
  
  .title-with-back {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .tasks-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}

/* 表格样式优化 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table :deep(.el-table__header) {
  background-color: #f8fafc;
}

.el-table :deep(.el-table__row:hover) {
  background-color: #f0f9ff;
}

/* 标签样式 */
.el-tag {
  border-radius: 6px;
  font-weight: 500;
}

/* 任务名称搜索样式 */
.task-name-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 0;
}

.task-name-item .el-icon {
  color: #409eff;
  font-size: 16px;
}

.task-name-item span {
  font-size: 14px;
  color: #303133;
}

/* 清空任务统计样式 */
.clear-task-stats {
  background-color: #fef0f0;
  border-radius: 8px;
  padding: 20px;
  border-left: 4px solid #f56c6c;
  text-align: center;
}

.clear-task-stats .stats-item {
  display: flex;
  align-items: baseline;
  justify-content: center;
  gap: 8px;
}

.clear-task-stats .stats-value.total {
  font-size: 36px;
  font-weight: bold;
  color: #f56c6c;
  line-height: 1;
}

.clear-task-stats .stats-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

/* 任务表格固定高度样式 */
.tasks-table {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
}

.tasks-table :deep(.el-table__body-wrapper) {
  /* 确保滚动条样式美观 */
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}

.tasks-table :deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

.tasks-table :deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 4px;
}

.tasks-table :deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 4px;
}

.tasks-table :deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}

/* 表格头部固定样式 */
.tasks-table :deep(.el-table__header-wrapper) {
  background-color: #fafafa;
  border-bottom: 2px solid #e4e7ed;
}

/* 表格行悬停效果 */
.tasks-table :deep(.el-table__row:hover) {
  background-color: #f0f9ff !important;
}

/* 事务管理样式 */
.transaction-query-form {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.transactions-table {
  margin-bottom: 16px;
}

.transaction-stats {
  padding: 12px 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  text-align: center;
}

.batch-rollback-form {
  padding: 16px 0;
}

.batch-rollback-form .el-form-item {
  margin-bottom: 20px;
}

.batch-rollback-form .el-alert {
  margin-bottom: 20px;
}

/* 事务管理响应式 */
@media (max-width: 768px) {
  .transaction-query-form .el-form {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
  
  .transaction-query-form .el-form-item {
    margin-right: 0;
    margin-bottom: 12px;
  }
  
  .transactions-table {
    overflow-x: auto;
  }
}

/* 统一的对话框样式 */
/* 对话框已使用统一样式系统 (dialog-system.css) */

/* 对话框内容区域 */
.task-query-dialog :deep(.el-dialog__body),
.stop-task-dialog :deep(.el-dialog__body),
.clear-task-dialog :deep(.el-dialog__body),
.transaction-query-dialog :deep(.el-dialog__body),
.batch-rollback-dialog :deep(.el-dialog__body),
.sql-execute-dialog :deep(.el-dialog__body),
.connection-test-dialog :deep(.el-dialog__body),
.task-detail-dialog :deep(.el-dialog__body) {
  padding: 24px;
}

/* 对话框footer样式 */
.task-query-dialog :deep(.el-dialog__footer),
.stop-task-dialog :deep(.el-dialog__footer),
.clear-task-dialog :deep(.el-dialog__footer),
.transaction-query-dialog :deep(.el-dialog__footer),
.batch-rollback-dialog :deep(.el-dialog__footer),
.sql-execute-dialog :deep(.el-dialog__footer),
.connection-test-dialog :deep(.el-dialog__footer),
.task-detail-dialog :deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 对话框表单优化 */
.task-query-dialog :deep(.el-form-item),
.stop-task-dialog :deep(.el-form-item),
.clear-task-dialog :deep(.el-form-item),
.transaction-query-dialog :deep(.el-form-item),
.batch-rollback-dialog :deep(.el-form-item),
.sql-execute-dialog :deep(.el-form-item),
.connection-test-dialog :deep(.el-form-item),
.task-detail-dialog :deep(.el-form-item) {
  margin-bottom: 20px;
}

/* 任务详情对话框样式 */
.task-detail-content {
  max-height: 70vh;
  overflow-y: auto;
}

.task-detail-descriptions {
  margin-bottom: 24px;
}

.task-detail-descriptions :deep(.el-descriptions__label) {
  font-weight: 600;
  background-color: #f5f7fa;
}

.sql-definition-container {
  margin-top: 16px;
}

.sql-definition-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 12px;
  background: #f5f7fa;
  border-radius: 6px;
}

.sql-actions {
  display: flex;
  gap: 8px;
}

.sql-textarea {
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
}

.sql-textarea :deep(.el-textarea__inner) {
  background-color: #f5f7fa;
  color: #303133;
  border: 1px solid #dcdfe6;
  line-height: 1.6;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
}

.sql-textarea :deep(.el-textarea__inner):focus {
  background-color: #fff;
  border-color: #409eff;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  margin: 0;
  min-width: 70px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.action-buttons .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.action-buttons .el-button.is-plain {
  border-width: 1px;
}

.action-buttons .el-button--primary.is-plain {
  color: #409eff;
  background: #ecf5ff;
  border-color: #b3d8ff;
}

.action-buttons .el-button--primary.is-plain:hover {
  background: #409eff;
  border-color: #409eff;
  color: #fff;
}

.action-buttons .el-button--danger.is-plain {
  color: #f56c6c;
  background: #fef0f0;
  border-color: #fbc4c4;
}

.action-buttons .el-button--danger.is-plain:hover {
  background: #f56c6c;
  border-color: #f56c6c;
  color: #fff;
}

/* 操作列样式优化 */
.tasks-table :deep(.el-table__fixed-right) {
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.06);
}

/* 全屏按钮样式 */
.fullscreen-btn {
  position: absolute;
  right: 50px;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(64, 158, 255, 0.1);
  border: 1px solid rgba(64, 158, 255, 0.3);
  color: #409eff;
  transition: all 0.3s ease;
}

.fullscreen-btn:hover {
  background: rgba(64, 158, 255, 0.2);
  border-color: #409eff;
  transform: translateY(-50%) scale(1.1);
}

.fullscreen-btn:active {
  transform: translateY(-50%) scale(0.95);
}

/* 全屏时的对话框样式优化 */
.task-query-dialog.is-fullscreen :deep(.el-dialog__body),
.transaction-query-dialog.is-fullscreen :deep(.el-dialog__body) {
  padding: 20px 24px;
  max-height: calc(100vh - 150px);
  overflow-y: auto;
}
</style>

